//
//  OtherFavoriteCtrl.m
//  cutter
//
//  Created by mac on 16/3/7.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherCenter.h"
#import "OtherFavoriteCtrl.h"
#import "ProductDetailCtrl.h"
#import "SpaceEditController.h"
#import "MatchDetailCtrl.h"
//
@implementation OtherFavoriteCell
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    [self.selectView setSelected:selected];
}
@end

//
@implementation OtherFavoriteCtrl
-(void)viewDidLoad {
    [super viewDidLoad];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.deleteView setHidden:YES];
    [self.editView addTarget:self action:@selector(editTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.deleteView addTarget:self action:@selector(deleteTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView setAllowsMultipleSelection:YES];
    //
    [self.schemeView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.productView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.matchView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    OtherCenter *center = (id)self.splitViewController;
    if ([center isKindOfClass:OtherCenter.class] && center.userCenterCtrl) {
        [self setClient:center.userCenterCtrl.client];
        [self typeTouch:self.schemeView];
    }
}
- (void)typeTouch:(UIButton*)sender{
    [self.schemeView setSelected:NO];
    [self.productView setSelected:NO];
    [self.matchView setSelected:NO];
    [sender setSelected:YES];
    //
    if (sender == self.schemeView) {
        [self.condition setValue:@"suit" forKey:@"t"];
    }else if (sender == self.productView) {
        [self.condition setValue:@"product" forKey:@"t"];
    }else{
        [self.condition setValue:@"match" forKey:@"t"];
    }
    //
    [self headerRefresh:nil];
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak OtherFavoriteCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userFavorite:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.collectionView.footerView setFinish:NO];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak OtherFavoriteCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userFavorite:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.condition setValue:textField.text forKey:@"keyword"];
    [self headerRefresh:nil];
    return YES;
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(10000) forKey:@"limit"];
    [_condition setValue:[self.client objectForKey:@"uuid"] forKey:@"clientuuid"];
    return _condition;
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [self.data objectAtIndex:indexPath.item];
    [item setValue:[self.condition objectForKey:@"t"] forKey:@"t"];
    if ([[item objectForKey:@"t"] isEqualToString:@"product"]) {
        OtherFavoriteCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"productIdentifier" forIndexPath:indexPath];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
        [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
        [cell.selectView setHidden:!self.editView.selected];
        return cell;
    }
    if ([[item objectForKey:@"t"] isEqualToString:@"match"]) {
        OtherFavoriteCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"matchIdentifier" forIndexPath:indexPath];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"matchname"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
        [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
        [cell.selectView setHidden:!self.editView.selected];
        return cell;
    }
    //
    if ([item objectForKey:@"pic2"]) {
        [item setValue:[item objectForKey:@"pic2"] forKey:@"pic"];
        [item setValue:nil forKey:@"pic2"];
    }
    if ([item objectForKey:@"json2"]) {
        [item setValue:[item objectForKey:@"json2"] forKey:@"json"];
        [item setValue:nil forKey:@"json2"];
    }
    OtherFavoriteCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"schemeIdentifier" forIndexPath:indexPath];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"suitname"] lable:nil]];
    [cell.priceView setText:[AppData areaToString:[item objectForKey:@"spacearea"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    [cell.selectView setHidden:!self.editView.selected];
    return cell;
}
//
- (void)editTouch:(UIButton*)sender{
    [sender setSelected:!sender.selected];
    [self.deleteView setHidden:!sender.selected];
    //
    NSArray *cells = [self.collectionView visibleCells];
    for (OtherFavoriteCell *cell in cells) {
        if ([cell isKindOfClass:OtherFavoriteCell.class]) {
            [cell.selectView setHidden:!sender.selected];
        }
    }
}
-(void)deleteTouch:(UIButton*)sender{
    NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
    if ([indexPaths count] > 0) {
        __weak OtherFavoriteCtrl *this = self;
        [UIAlertController show:nil message:@"删除选中收藏?" buttons:@[@"删除",@"取消"] handler:^(UIAlertAction *action) {
            if ([action.title isEqualToString:@"删除"]) {
                NSMutableArray *removedPaths = [NSMutableArray array];
                for (NSIndexPath *indexPath in indexPaths) {
                    id item = [self.data objectAtIndex:indexPath.item];
                    if ([AppData userDeleteFavorite:item client:this.client]) {
                        [removedPaths addObject:indexPath];
                    }
                }
                if (removedPaths.count > 0) {
                    NSMutableArray *temps = [NSMutableArray array];
                    for (uint i=0; i<this.data.count; i++) {
                        BOOL removed = NO;
                        for (NSIndexPath *indexPath in removedPaths) {
                            if (indexPath.item == i) {
                                removed = YES;
                                break;
                            }
                        }
                        if (removed == NO) {
                            [temps addObject:[self.data objectAtIndex:i]];
                        }
                    }
                    [this setData:temps];
                    [this.collectionView deleteItemsAtIndexPaths:removedPaths];
                }
                [this editTouch:this.editView];
            }
        }];
    }
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([self.deleteView isHidden] == NO) {
        return NO;
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
    if (indexPath) {
        id data = [self.data objectAtIndex:indexPath.item];
        UIViewController *ctrl = segue.destinationViewController;
        if ([ctrl isKindOfClass:ProductDetailCtrl.class]) {
            ProductDetailCtrl *tmp = (id)ctrl;
            [tmp setData:data];
        }
        if ([ctrl isKindOfClass:MatchDetailCtrl.class]) {
            MatchDetailCtrl *tmp = (id)ctrl;
            [tmp setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:nil];
            }];
            [tmp setData:data];
        }
        if ([ctrl isKindOfClass:SpaceEditController.class]) {
            SpaceEditController *detail = segue.destinationViewController;
            [detail setTitleName:[data objectForKey:@"suitname"]];
            [detail setSource:data];
        }
    }
}
@end
